package cn.edu.xmu.rocketmqdemo.controller;

import cn.edu.xmu.rocketmqdemo.model.OrderVo;
import cn.edu.xmu.rocketmqdemo.model.VoObject;
import cn.edu.xmu.rocketmqdemo.service.OrdersService;
import cn.edu.xmu.rocketmqdemo.service.RocketMQService;
import cn.edu.xmu.rocketmqdemo.util.ResponseCode;
import cn.edu.xmu.rocketmqdemo.util.ResponseUtil;
import cn.edu.xmu.rocketmqdemo.util.ReturnObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping(value = "/orders")
public class OrdersController{

    @Autowired
    public OrdersService ordersService;
    @Autowired
    public RocketMQService rocketMQService;

    @GetMapping("{id}")
    public Object findOrderById(@PathVariable("id") Integer id) {
        ReturnObject<VoObject> returnObject = ordersService.findOrderById(id);
        ResponseCode responseCode = returnObject.getCode();
        switch (responseCode) {
            case OK:
                return ResponseUtil.ok(returnObject.getData().createVo());
            case RESOURCE_ID_NOTEXIST:
                return ResponseUtil.fail(returnObject.getCode(), returnObject.getErrmsg());
            default:
                return ResponseUtil.fail(returnObject.getCode());
        }
    }

    @PostMapping("")
    public Object createOrder(@RequestBody OrderVo orderVo){
        rocketMQService.sendOrderMessage(orderVo);
        ReturnObject<VoObject> returnVo = rocketMQService.getReturnVo();
        ResponseCode responseCode = returnVo.getCode();
        if (responseCode.equals(ResponseCode.OK)){
                return ResponseUtil.ok(returnVo.getData());
        }else{
            return ResponseUtil.fail(returnVo.getCode(),returnVo.getErrmsg());
        }
    }


}
